package com.googlecode.agscrum.controller.spring;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;

import com.googlecode.agscrum.model.entity.User;
import com.googlecode.agscrum.model.exceptions.GScrumDomainException;
import com.googlecode.agscrum.model.service.UserService;

public class UserDetailsServiceImpl implements UserDetailsService {

	private UserService userService;

	public UserDetailsServiceImpl(UserService userService) {
		this.userService = userService;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = null;
		try {
			user = userService.readByLogin(username);
		} catch (GScrumDomainException e) {

		}
		if (user == null)
			throw new UsernameNotFoundException("User not found: " + username);
		else {
			return makeAcegiUser(user);
		}
	}

	private org.acegisecurity.userdetails.User makeAcegiUser(User user) {
		return new org.acegisecurity.userdetails.User(user.getLogin(), user
				.getPassword(), true, true, true, true,
				makeGrantedAuthorities(user));
	}

	private GrantedAuthority[] makeGrantedAuthorities(User user) {
		GrantedAuthority[] result = new GrantedAuthority[1];
		result[0] = new GrantedAuthorityImpl("ALL");
		return result;
	}

}
